package com.woniuxy.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.finance.mapper.AccountManageMapper;
import com.woniuxy.finance.mapper.BlotterMapper;
import com.woniuxy.finance.mapper.BusinessCompetitorMapper;
import com.woniuxy.finance.model.dto.ConditionAccDto;
import com.woniuxy.finance.model.dto.FindBlotterDto;
import com.woniuxy.finance.model.dto.RechargeDto;
import com.woniuxy.finance.model.entity.Blotter;
import com.woniuxy.finance.model.entity.BusinessCompetitor;
import com.woniuxy.finance.model.entity.Recharge;
import com.woniuxy.finance.mapper.RechargeMapper;
import com.woniuxy.finance.model.vo.CountClientVo;
import com.woniuxy.finance.model.vo.FindUpdateVo;
import com.woniuxy.finance.service.RechargeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.model.entity.AccountManage;
import com.woniuxy.model.vo.UpdateSaleMoneyVo;
import com.woniuxy.model.vo.UpdateSaleOrderVo;
import com.woniuxy.service.FeignSaleMoneyService;
import com.woniuxy.service.FeignSaleOrderService;
import com.woniuxy.util.SnowflakeIdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户充值表; 服务实现类
 * </p>
 *
 * @author chenlin
 * @since 2023-09-06
 */
@Service
public class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements RechargeService {
    @Resource
    private RechargeMapper rechargeMapper;
    @Resource
    private FeignSaleMoneyService saleMoneyService;
    @Resource
    private FeignSaleOrderService saleOrderService;
    @Resource
    private BusinessCompetitorMapper businessCompetitorMapper;
    @Resource
    private AccountManageMapper accountManageMapper;
    @Resource
    private BlotterMapper blotterMapper;

    /**
     * 添加一条充值信息
     * @param recharge
     * @return
     */
    @Override
    @Transactional
    public boolean addRecharge(Recharge recharge,String account) {
        //获取当前时间
        String date =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        recharge.setCreateTime(date);
        recharge.setAdminName(account);
        String a = SnowflakeIdWorker.newId()+"";
        //充值单号
        recharge.setRechargeNumber(a);
        BusinessCompetitor businessCompetitor = new BusinessCompetitor();
        businessCompetitor.setBalance(recharge.getMoney());
        businessCompetitor.setName(recharge.getUserName());
        Blotter blotter = new Blotter();
        blotter.setName(recharge.getUserName());
        blotter.setTotalPrice(recharge.getMoney());
        blotter.setAdminName(account);
        blotter.setCreateTime(date);
        blotter.setSno(a);
            //修改客户的余额
            if(businessCompetitorMapper.updateBalanceByName(businessCompetitor)){
                //设置状态
                recharge.setStatus("0");
                //插入充值记录
                rechargeMapper.insert(recharge);
                //插入流水
                blotter.setStatus("0");
                int i = blotterMapper.insert(blotter);
                if(i > 0){
                    return true;
                }
                return false;
            }
            return false;
    }
    /**
     * 多条件查询充值
     * @param rechargeDTO
     * @return
     */
    @Override
    public Page<Recharge> conditions(RechargeDto rechargeDTO) {
        LambdaQueryWrapper<Recharge> lqw = new LambdaQueryWrapper<>();
        lqw.like(rechargeDTO.getRechargeNum() != null,Recharge::getRechargeNumber,rechargeDTO.getRechargeNum())
                .between(rechargeDTO.getStartTime() != null,Recharge::getCreateTime,rechargeDTO.getStartTime(),rechargeDTO.getEndTime());
        return rechargeMapper.selectPage(new Page<>(rechargeDTO.getPage(),rechargeDTO.getSize()),lqw);
//        return rechargeMapper.conditions(rechargeDTO);
    }

    /**
     * 修改充值
     * @param recharge
     * @return
     */
    @Transactional
    @Override
    public boolean updateRecharge(Recharge recharge) {
        //根据id获取修改前的充值信息
        Recharge r1 = rechargeMapper.selectById(recharge.getId());
        //根据名称减去客户原来的充值金额 在+修改后的金额
        BusinessCompetitor b = new BusinessCompetitor();
        b.setName(r1.getUserName());
        BigDecimal balance = businessCompetitorMapper.findBalanceByName(b);
        if(balance.compareTo(r1.getMoney()) < 0){
            if(r1.getMoney().compareTo(recharge.getMoney()) < 0){
                b.setBalance(r1.getMoney());
                businessCompetitorMapper.deductBalanceByName(b);//扣除上次充值金额
                b.setBalance(recharge.getMoney());
                businessCompetitorMapper.updateBalanceByName(b);//加上本次修改后的金额
                //修改数据
                String now =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                recharge.setCreateTime(now);
                if(rechargeMapper.updateById(recharge) > 0){
                    //添加修改记录
                    Recharge r = rechargeMapper.selectById(recharge.getId());
                    rechargeMapper.insertUpdate(r);
                    return true;
                }
            }
            return false;
        }
        b.setBalance(r1.getMoney());
        businessCompetitorMapper.deductBalanceByName(b);//扣除上次充值金额
        b.setBalance(recharge.getMoney());
        businessCompetitorMapper.updateBalanceByName(b);//加上本次修改后的金额
        //修改数据
        String now =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        recharge.setCreateTime(now);
        if(rechargeMapper.updateById(recharge) > 0){
            //添加修改记录
            Recharge r = rechargeMapper.selectById(recharge.getId());
            rechargeMapper.insertUpdate(r);
            return true;
        }
        return false;
    }
    /**
     * 查看修改记录
     * @param id
     * @return
     */
    @Override
    public List<FindUpdateVo> findUpdate(Integer id) {
        return rechargeMapper.findUpdate(id);
    }
    /**
     * 根据id删除充值单
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean delRecharge(Integer id) {
        //查询出本单的充值金额和客户名
        Recharge r = rechargeMapper.selectById(id);
        //删除之前要减去本单的金额
        BusinessCompetitor b = new BusinessCompetitor();
        b.setName(r.getUserName());
        //根据名称获取余额
        BigDecimal balance = businessCompetitorMapper.findBalanceByName(b);
        if(balance.compareTo(r.getMoney()) < 0){//判断余额是否足够
            return false;
        }
        b.setBalance(r.getMoney());
        //根据客户名扣除充值金额
        businessCompetitorMapper.deductBalanceByName(b);
        int i = rechargeMapper.deleteById(id);
        if(i > 0){
            return true;
        }
        return false;
    }

    /**
     * 分页查询账户管理
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<AccountManage> findAccountManage(Integer page, Integer size) {
        Page<AccountManage> pages = accountManageMapper.selectPage(new Page<>(page, size), null);
        return pages;
    }

    /**
     * 添加一条账户管理
     * @param accountManage
     * @return
     */
    @Transactional
    @Override
    public boolean addAccountManage(AccountManage accountManage) {
        if(accountManageMapper.insert(accountManage) > 0){
            return true;
        }
        return false;
    }
    /**
     * 多条件查询账户
     */
    @Override
    public Page<AccountManage> conditionsAccount(String userName,String aLock,Integer page,Integer size) {
        LambdaQueryWrapper<AccountManage> lqw = new LambdaQueryWrapper<>();
        lqw.like(userName != null,AccountManage::getUserName,userName)
                .like(aLock != null,AccountManage::getALock,aLock);
        return accountManageMapper.selectPage(new Page<>(page,size),lqw);
    }
    /**
     * 锁定
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean lock(Integer id) {
        AccountManage account = new AccountManage();
        account.setId(id);
        account.setALock("1");
        if(accountManageMapper.updateById(account) > 0){
            return true;
        }
        return false;
    }
    /**
     * 解除锁定
     * @param id
     * @return
     */
    @Transactional
    @Override
    public boolean unlock(Integer id) {
        AccountManage account = new AccountManage();
        account.setId(id);
        account.setALock("0");
        if(accountManageMapper.updateById(account) > 0){
            return true;
        }
        return false;
    }
    /**
     * 扣除账户应缴费用
     */
    @GlobalTransactional
    @Override
    public boolean updatemoney(Integer id,String aname) {
        //根据id获取账户详情
        AccountManage account = accountManageMapper.selectById(id);
        BusinessCompetitor businessCompetitor = new BusinessCompetitor();
        AccountManage a = new AccountManage();
        a.setId(id);
        a.setStatus("0");
        a.setReceivableMoney(account.getReceivableMoney());

        Blotter blotter = new Blotter();
        blotter.setName(account.getUserName());
        blotter.setSno(account.getSno());
        blotter.setTotalPrice(account.getReceivableMoney());
        blotter.setAdminName(account.getAdminName());
        blotter.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        UpdateSaleMoneyVo updateSaleMoneyVo = new UpdateSaleMoneyVo();
        updateSaleMoneyVo.setSno(account.getSno());
        updateSaleMoneyVo.setState("2");
        updateSaleMoneyVo.setType(account.getMoneyType());
        updateSaleMoneyVo.setOperator(aname);

        if("退款".equals(account.getMoneyType())){
            businessCompetitorMapper.updateBalanceByName(businessCompetitor);
            //修改账户管理表余额、状态
            accountManageMapper.updateBalanceById(a);
            //修改退款账单状态
            saleMoneyService.updateState2(updateSaleMoneyVo);
            //
            //插入流水
            blotter.setStatus("3");
            int i = blotterMapper.insert(blotter);
            if(i > 0){
                return true;
            }
            return false;
        }
        //获取客户余额
        businessCompetitor.setName(account.getUserName());
        BigDecimal balance = businessCompetitorMapper.findBalanceByName(businessCompetitor);
        if(balance.compareTo(account.getReceivableMoney()) >= 0){
            //余额足
            businessCompetitor.setBalance(account.getReceivableMoney());
            //扣除费用
            boolean b = businessCompetitorMapper.deductBalanceByName(businessCompetitor);
            //修改账户管理表的余额、状态
            accountManageMapper.updateBalanceById(a);
            //根据选货单单号修改选货单状态
            saleMoneyService.updateState2(updateSaleMoneyVo);
            if ("定金".equals(account.getMoneyType())){
                //已付定金
                UpdateSaleOrderVo updateSaleOrderVo = new UpdateSaleOrderVo();
                updateSaleOrderVo.setSno(account.getSno());
                updateSaleOrderVo.setState("3");
                saleOrderService.updateState(updateSaleOrderVo);
                //插入流水
                blotter.setStatus("1");
                blotterMapper.insert(blotter);
            }else{
                //已付尾款
                UpdateSaleOrderVo updateSaleOrderVo = new UpdateSaleOrderVo();
                updateSaleOrderVo.setSno(account.getSno());
                updateSaleOrderVo.setState("5");
                saleOrderService.updateState(updateSaleOrderVo);
                //插入流水
                blotter.setStatus("2");
                blotterMapper.insert(blotter);
            }
            return b;
        }
        return false;
    }

    /**
     * 统计客户信息和充值总额
     * @param page
     * @param size
     * @return
     */
    @Override
    public IPage<CountClientVo> countClientData(Integer page, Integer size) {
        Page<CountClientVo> voPage = new Page<>(page, size);
        return businessCompetitorMapper.countClientData(voPage);
    }

    @Override
    public IPage<Blotter> findBlotter(FindBlotterDto blotterDto) {
        Blotter blotter = new Blotter();
        blotter.setName(blotterDto.getName());
        LambdaQueryWrapper lqw = new LambdaQueryWrapper<>(blotter).orderByDesc(Blotter::getCreateTime);
        Page<Blotter> page = blotterMapper.selectPage(new Page<>(blotterDto.getPage(), blotterDto.getSize()), lqw);
        return page;

    }

    /**
     * 查询所有客户充值信息
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Recharge> findRecharge(Integer page, Integer size) {
        Recharge recharge = new Recharge();
        recharge.setStatus("0");
        LambdaQueryWrapper lqw = new LambdaQueryWrapper<>(recharge);
        return rechargeMapper.selectPage(new Page<>(page,size),lqw);
    }
}
